package nl.dxn.tunnel.client.handel;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.internal.EmptyArrays;
import nl.dxn.tunnel.client.Constants;
import nl.dxn.tunnel.client.executors.AuthExecutor;
import nl.dxn.tunnel.enums.TransferMessageType;
import nl.dxn.tunnel.po.MessageConfig;
import nl.dxn.tunnel.po.TransferMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TcpClientHandel extends ChannelInboundHandlerAdapter {
    private final MessageConfig messageConfig;

    private static final Logger logger = LoggerFactory.getLogger(ProxyTcpHandler.class);

    public TcpClientHandel(final MessageConfig messageConfig) {
        this.messageConfig = messageConfig;
    }

    /**
     * 连接初始化，建立连接
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf readBuffer = (ByteBuf) msg;
            byte[] data = new byte[readBuffer.readableBytes()];
            readBuffer.readBytes(data);
            readBuffer.release();

            Channel proxy = ctx.channel().attr(Constants.PROXY).get();
            if (proxy == null) {
                ctx.close();
                return;
            }

            TransferMessage message = new TransferMessage();
            message.setData(data);
            message.setType(TransferMessageType.TYPE_DATA);
            message.getConfig().setChannelId(messageConfig.getChannelId());

            proxy.writeAndFlush(message);
        } catch (Exception ex) {
            logger.error("", ex);
        }
//        finally {
//            ReferenceCountUtil.release(msg);
//        }
    }

    /**
     * 连接中断
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            Channel proxy = ctx.channel().attr(Constants.PROXY).get();
            if (proxy == null) {
                ctx.close();
                return;
            }

            TransferMessage resultMassage = new TransferMessage();
            resultMassage.setConfig(messageConfig);
            resultMassage.setData(EmptyArrays.EMPTY_BYTES);
            resultMassage.setType(TransferMessageType.TYPE_DISCONNECTED);
            resultMassage.getConfig().setResult("代理客户端远程地址连接断开");
            proxy.writeAndFlush(resultMassage);

            AuthExecutor.disConnectFromAgent(proxy, ctx.channel());
        }
        catch (Exception ex)
        {
            logger.error("",ex);
        }
        ctx.close();
    }

    /**
     * 连接异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("",cause);
        ctx.close();
    }
}
